<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input
                v-model="listQuery.search"
                placeholder="请输入 版本名称|版本号"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="handleFilter"
            />
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                {{ $t('table.search') }}
            </el-button>
            <el-button v-if="permission.delete.status" v-waves class="filter-item" type="danger" icon="el-icon-delete" @click="handleDelete">
                {{ $t('table.batchDelete') }}
            </el-button>
            <el-button
                v-if="permission.create.status"
                class="filter-item"
                style="margin-left: 10px;"
                type="primary"
                icon="el-icon-plus"
                @click="handleEdit"
            >
                {{ $t('table.add') }}
            </el-button>
            <el-button
                v-waves
                :loading="downloadLoading"
                class="filter-item"
                type="success"
                icon="el-icon-download"
                @click="handleDownload"
            >
                {{ $t('table.export') }}
            </el-button>
        </div>

        <el-table
            v-loading="listLoading"
            :data="list"
            :element-loading-text="elementLoadingText"
            @selection-change="setSelectRows"
            border
            class="margin-buttom-10"
        >
            <el-table-column show-overflow-tooltip type="selection"/>
            <el-table-column
                show-overflow-tooltip
                prop="version_id"
                label="Id"
                align="center"
            />

            <el-table-column
                show-overflow-tooltip
                prop="version_name"
                label="版本名称"
                align="center"
            />

            <el-table-column
                show-overflow-tooltip
                prop="version_number"
                label="版本号"
                align="center"
            />

            <el-table-column
                show-overflow-tooltip
                prop="version_sort"
                label="排序"
                align="center"
            />

            <el-table-column
                show-overflow-tooltip
                prop="publish_date"
                label="版本发布时间"
                align="center"
            />

            <el-table-column label="创建时间" show-overflow-tooltip align="center">
                <template slot-scope="{ row }">
                    {{ row.created_time | parseTime("{y}-{m}-{d} {h}:{i}") }}
                </template>
            </el-table-column>

            <el-table-column
                fixed="right"
                label="操作"
                align="center"
            >
                <template v-slot="{row}">
                    <!-- 编辑与删除 -->
                    <el-button v-if="permission.update.status" type="text" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
                    <el-button v-if="permission.delete.status" type="text" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            :current-page="listQuery.page"
            :page-size="listQuery.limit"
            :layout="layout"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <!-- 详情 -->
        <edit ref="edit" @fetchData="getList"/>
    </div>
</template>

<script>
    import { checkButtonPermission } from '@/utils/permission';
    import {getList, create, update, setDel} from '@/api/versions';
    import waves from '@/directive/waves'; // waves directive
    import Edit from './components/detail';
    import {parseTime, getFormatDate} from '@/utils/index';

    export default {
        name: 'versionsManage',
        components: {Edit},
        directives: {waves},
        filters: {
            parseTime: parseTime,
            getFormatDate: getFormatDate,
        },
        data() {
            return {
                is_batch: 0, // 默认不开启批量删除
                list: [],
                listLoading: true,
                layout: 'total, sizes, prev, pager, next, jumper',
                total: 0,
                selectRows: '',
                elementLoadingText: '正在加载...',
                listQuery: {
                    page: 1,
                    limit: 10,
                    search: '',
                    is_check: '',
                    is_download: 0, // 是否下载：1.是；默认0
                },
                downloadLoading: false,
                // 权限状态
                permission: {
                    create: {
                        url: '',
                        status: false,
                    },
                    update: {
                        url: '',
                        status: false,
                    },
                    delete: {
                        url: '',
                        status: false,
                    },
                }
            }
        },
        created() {
            this.getList();
            // 验证当前页面的按钮权限
            let apis = [];
            this.permission.create.url = create({}, true);
            this.permission.update.url = update({}, true);
            this.permission.delete.url = setDel({}, true);
            apis.push(this.permission.create.url);
            apis.push(this.permission.update.url);
            apis.push(this.permission.delete.url);
            // 验证权限按钮
            checkButtonPermission(this, apis);
        },
        methods: {
            setSelectRows(val) {
                this.selectRows = val;
                this.is_batch = 1;
            },
            handleEdit(row) {
                if (row) {
                    this.$refs['edit'].showEdit(row);
                } else {
                    this.$refs['edit'].showEdit({});
                }
            },
            handleDelete(row) {
                var ids = '';
                if (row.version_id) {
                    ids = row.version_id;
                } else {
                    if (this.selectRows.length > 0) {
                        ids = this.selectRows.map((item) => item.version_id).join();
                    } else {
                        this.$message('未选中任何行', 'error');
                        return false;
                    }
                }

                // 删除流程
                this.$confirm(
                    '你确定要删除操作吗？删除之后将无法恢复，请谨慎操作',
                    'Warning',
                    {
                        confirmButtonText: 'Confirm',
                        cancelButtonText: 'Cancel',
                        type: 'warning'
                    })
                    .then(async () => {
                        const {status, msg} = await setDel({version_id: ids, 'is_batch': this.is_batch});

                        switch (status) {
                            case 1:
                                this.getList();

                                this.$message({
                                    type: 'success',
                                    message: msg
                                });
                                break;
                            default:
                                this.$message({
                                    type: 'error',
                                    message: msg
                                });
                                break;
                        }

                    })
                    .catch(err => {
                        console.error(err);
                    })
            },
            handleSizeChange(val) {
                this.listQuery.limit = val;
                this.listQuery.is_download = 0;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.listQuery.is_download = 0;
                this.getList();
            },
            handleFilter() {
                this.listQuery.page = 1;
                this.listQuery.is_download = 0;
                this.getList();
            },
            async getList(callback) {
                this.listLoading = true;
                const {data, status, msg} = await getList(this.listQuery);
                if (this.listQuery.is_download == 1) {
                    if (callback) {
                        callback(data, status, msg);
                    }
                } else {
                    this.list = data.data;
                    this.total = data.total;
                    this.listQuery.limit = data.per_page || 10;
                }
                setTimeout(() => {
                    this.listLoading = false;
                }, 300);
            },
            // 导出
            handleDownload() {
                this.downloadLoading = true;
                this.listQuery.page = 1;
                this.listQuery.is_download = 1;
                let _this = this;
                this.getList(function (data, status, msg) {
                    // 如果获取失败，那么无需进入下一步
                    if (status != 1) {
                        _this.$message({
                            message: msg,
                            type: 'error',
                        });
                        return;
                    }
                    // 开始导出
                    import('@/vendor/Export2Excel').then((excel) => {
                        const tHeader = [
                            'Id',
                            '版本名称',
                            '版本号',
                            '版本内容',
                            '排序',
                            '版本发布时间',
                            '创建时间',
                        ];
                        const filterVal = [
                            'version_id',
                            'version_name',
                            'version_number',
                            'version_content',
                            'version_sort',
                            'publish_date',
                            'created_time',
                        ];
                        const download_list_data = _this.formatJson(data, filterVal);
                        excel.export_json_to_excel({
                            header: tHeader,
                            data: download_list_data,
                            filename: '版本列表-' + getFormatDate(),
                        });
                        _this.downloadLoading = false;
                    })
                })
            },
            formatJson(data, filterVal) {
                return data.map((v) =>
                    filterVal.map((j) => {
                        switch (j) {
                            case 'created_time':
                                return parseTime(v[j]) || '';
                                break;
                            default:
                                return v[j];
                                break;
                        }
                    })
                ) || [];
            },
        }
    }
</script>
